function appendRow(pFrm, id)
{
    var f = document.getElementById(pFrm);
    var tb = document.getElementById(id).getElementsByTagName('tBody')[0];
    var r = tb.getElementsByTagName('tr')[1].cloneNode(true);
    var lastRec = f.recLines.value * 1;
    tb.appendChild(r);
    f.amount[lastRec].value = "";
    f.recLines.value = f.recLines.value * 1 + 1;
}

function delRow(pFrm, modo, id)
{
    var f = document.getElementById(pFrm);
    var tbody = document.getElementById(id).getElementsByTagName('tBody')[0];
    var lastRec = f.recLines.value * 1;
    if (lastRec > 1)
    {
        if (modo==0) tbody.deleteRow(lastRec);
        if (modo==1) tbody.removeChild(tbody.lastChild);
        f.recLines.value = lastRec - 1;
    }
}

function addAmount(pFrm, pId,pType)
{
   
    var f = document.getElementById(pFrm);
    var cTipoPayment = String(pType);

    var payment = document.getElementById(pId);
    var tendered = 0;
    var credit = f.credit.value;
    var totalDue = f.totalDue.value;
    var totalTendered = f.totalTendered.value;
    var balance = f.balance.value;
    var aux = 0;
    for (j=0; j<5; j++)
    {
        aux = f.amount[j].value;
        aux = getValue(aux);
        tendered = tendered + aux;
    }
    credit = getValue(credit);
    totalDue = getValue(totalDue); 
    totalTendered = round(getValue(tendered) + credit);
    balance = round(totalTendered - totalDue);
    
    f.totalDue.value = commaFormatted(currencyFormatted(totalDue));
    f.totalTendered.value = commaFormatted(currencyFormatted(totalTendered));
    f.balance.value = commaFormatted(currencyFormatted(balance));
}

function round (value){
    return Math.round(value*100)/100;
}

function msgConfirmation(message){
    var_result = confirm(message);

    return var_result;
}

function calculateTotal(pFrm, pId, pCash)
{
    var f = document.getElementById(pFrm);   
    var payment = document.getElementById(pId);
    var total = 0; 
    var aux = 0;
    var iter = f.elements.value;
    if (iter == 1) {
        aux = f.amount.value;
        aux = getValue(aux);
        total = total + aux;
    } else {
        for (j=0; j<iter; j++)
        {
            aux = f.amount[j].value;
            aux = getValue(aux);
            total = total + aux;
        }
    }  
    document.getElementById(pCash).value=total;
    f.totalAmount.value = commaFormatted(currencyFormatted(total));
}

function updateBalanceCredit(pFrm, pCuCredit)
{
    //  alert("here!");
    var f = document.getElementById(pFrm);
    var idCredit = document.getElementById(pCuCredit);
    var cuCredit = document.getElementById(pCuCredit).value;
    var aCreditH = document.getElementById('aCreditH').value;
    var cBalanceH = document.getElementById('cBalanceH');
    var cBalance = document.getElementsByTagName('span')[1].firstChild.nodeValue;
    var avCredit = document.getElementsByTagName('span')[2].firstChild.nodeValue;
    cuCredit = getValue(cuCredit);
    cBalance = getValue(cBalance);
    avCredit = getValue(avCredit);
    // alert("Current = " + cuCredit + ". Balance = " + cBalance + ". Available = " + avCredit);
    if (cuCredit > aCreditH)
    {
        alert("Sorry, the available credit has been exceeded. ");
        idCredit.value = commaFormatted(currencyFormatted(0));
        document.getElementsByTagName('span')[2].firstChild.nodeValue = aCreditH;
        f.credit.focus();
        return false;
    }
    cBalance = cBalance + cuCredit;
    avCredit = avCredit - cuCredit;
    cBalanceH.value = cBalance;
    document.getElementsByTagName('span')[1].firstChild.nodeValue = "$" + commaFormatted(currencyFormatted(cBalance));
    document.getElementsByTagName('span')[2].firstChild.nodeValue = "$" + commaFormatted(currencyFormatted(aCreditH - cuCredit));

    addAmount('createInvoiceFrm', idCredit);
    idCredit.value =commaFormatted(currencyFormatted(cuCredit)); 

    return true;
}

function validateForm(pFrm)
{
    var f = document.getElementById(pFrm);
    var formatedBalance = f.balance.value;
    var unformattedBalance = 0;
    unformattedBalance = getValue(formatedBalance);

    var formatedCash = f.amount[0].value;
    var unformattedCash = 0;
    unformattedCash = getValue(formatedCash);

    var formatedTotalDue = f.totalDue.value;
    var unformattedTotalDue = 0;
    unformattedTotalDue = getValue(formatedTotalDue);
    var change = unformattedCash - unformattedTotalDue;

    var formatedTotalTendered = f.totalTendered.value;
    var unformattedTotalTendered = 0;
    unformattedTotalTendered = getValue(formatedTotalTendered);

    if (unformattedBalance < 0)
    {
        alert("The balance ($ " + formatedBalance + ") cannot be diferent from zero to proceed.");
        return false;
    }

    if (unformattedTotalDue > 0){
        if (unformattedBalance > 0 )
        {
            if(unformattedCash > unformattedTotalDue)
            {
                if(change >= 100){
                    alert("Change $ " + change + ".");
                    return false;
                }else{
                    alert("Change $ " + change + ".");
                    return true;
                }
            }else
            {
                alert("The amount for those payments must be complete ($ " + unformattedTotalDue + ").");
                return false;
            }
        }
    }else{
        if(unformattedTotalTendered > 0){
            alert("Invoice already paid");
            return false;
        }
    }

    return(true);
}

function test(value)
{
    if (value==1){ 
        alert('shit');
        return false;
    }
    return(true);
}

function printWindow()
{
    window.print();
}

function patientBalance()
{
    window.open('patientBalance.jsf','QPharmacy','height=300,width=400,status=yes,toolbar=no,menubar=no,location=no'); 
    return(true);
}

function tables (str_tableid, // table id (req.)
num_header_offset, // how many rows to skip before applying effects at the begining (opt.)
num_footer_offset, // how many rows to skip at the bottom of the table (opt.)
str_odd_color, // background color for odd rows (opt.)
str_even_color, // background color for even rows (opt.)
str_mover_color, // background color for rows with mouse over (opt.)
str_onclick_color // background color for marked rows (opt.)
)
{

    //alert('ggg' + str_tableid);
    // skip non DOM browsers
    //if (typeof(document.all) != 'object') return;

    // validate required parameters
    if (!str_tableid) return alert ("No table(s) ID specified in parameters");
    var obj_tables = (document.all ? document.all[str_tableid] : document.getElementById(str_tableid));
    if (!obj_tables) return alert ("Can't find table(s) with specified ID (" + str_tableid + ")");

    // set defaults for optional parameters
    var col_config = [];
    col_config.header_offset = (num_header_offset ? num_header_offset : 0);
    col_config.footer_offset = (num_footer_offset ? num_footer_offset : 0);
    col_config.odd_color = (str_odd_color ? str_odd_color : '#ffffff');
    col_config.even_color = (str_even_color ? str_even_color : '#dbeaf5');
    col_config.mover_color = (str_mover_color ? str_mover_color : '#6699cc');
    col_config.onclick_color = (str_onclick_color ? str_onclick_color : '#FF6600');

    // init multiple tables with same ID
    if (obj_tables.length)
        for (var i = 0; i < obj_tables.length; i++)
            tt_init_table(obj_tables[i], col_config);
    // init single table
    else
        tt_init_table(obj_tables, col_config);
}

function tt_init_table (obj_table, col_config) {
    var col_lconfig = [],
    col_trs = obj_table.rows;
    for (var i = col_config.header_offset; i < col_trs.length - col_config.footer_offset; i++) {
        col_trs[i].config = col_config;
        col_trs[i].lconfig = col_lconfig;
        col_trs[i].set_color = tt_set_color;
        col_trs[i].onmouseover = tt_mover; 
        col_trs[i].onmouseout = tt_mout;
        col_trs[i].onmousedown = tt_onclick;
        col_trs[i].order = (i - col_config.header_offset) % 2;
        col_trs[i].onmouseout();
    }
}

function tt_set_color(str_color) {
    this.style.backgroundColor = str_color;
}

function tt_mover () {
    if (this.lconfig.clicked != this)
        this.set_color(this.config.mover_color);
}
function tt_mout () {
    if (this.lconfig.clicked != this)
        this.set_color(this.order ? this.config.odd_color : this.config.even_color);
}
function tt_onclick () {
    if (this.lconfig.clicked == this) {
        this.lconfig.clicked = null;
        this.onmouseover();
    }
    else {
        var last_clicked = this.lconfig.clicked;
        this.lconfig.clicked = this;
        if (last_clicked) last_clicked.onmouseout();
        this.set_color(this.config.onclick_color);
    }
}



function currencyFormatted(amount)
{
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

function commaFormatted(amount)
{
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.',2)
    var d = a[1];
    var i = parseInt(a[0]);
    if(isNaN(i)) { return ''; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while(n.length > 3)
    {
        var nn = n.substr(n.length-3);
        a.unshift(nn);
        n = n.substr(0,n.length-3);
    }
    if(n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if(d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

/*        new function */
function FSfncCheckCCexpire(FormField) {
    // Check credit expiry date is in valid format
    var CCexpire=FormField.value;
    if (CCexpire=="") {
        alert("Please enter your credit card expiry date.");
        FormField.focus(); 
        return false;
    }
    var ArrayCCexpr=CCexpire.split("/");
    if ((ArrayCCexpr.length!=2) || (ArrayCCexpr[0]=="") || (isNaN(ArrayCCexpr[0])) || (ArrayCCexpr[1]=="") || (isNaN(ArrayCCexpr[1])) || (ArrayCCexpr[0]<1) || (ArrayCCexpr[0]>12)) {
        alert("Alert: Expiry date is not in correct format, the correct format is MM/YY "); 
        FormField.focus(); 
        return false;
    }
    return true;
}


function getValue(num)
{
    var noJunk = ""
    var withDollar = ""
    var foundDecimal = 0
    var foundAlphaChar = 0
    num += "";

    if (num == "") { return(0); }
    for (i=0; i <= num.length; i++)
    {
        var thisChar = num.substring(i, i+1);
        if (thisChar == ".")
        {
            foundDecimal = 1;
            noJunk = noJunk + thisChar;
        }
        if ((thisChar < "0") || (thisChar > "9"))
        {
            if ((thisChar != "$") && (thisChar !=".") && (thisChar != ",") && (thisChar != " ") && (thisChar !="")) foundAlphaChar = 1;
        }
        else
        {
            withDollar = withDollar + thisChar
            noJunk = noJunk + thisChar
        }

        if ((thisChar == "$") || (thisChar == ".") || (thisChar == ","))
        {
            withDollar = withDollar + thisChar
        }
    }
    if (foundDecimal) { return parseFloat(noJunk); }
    else if (noJunk.length > 0) { return parseFloat(noJunk); }
    else return 0;
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function evalKeyPressed(e) { 
    var keyStroked 
    if (document.all) { 
        var e = window.event 
        keyStroked = e.keyCode 
    } else {
        keyStroked = e.which 
    }

    if ((keyStroked == 82)||(keyStroked == 114)) { 
        alert("red") 
    } 
} 

function ValidateAllFields(idForm)
{

    var f = document.getElementById(idForm);

    aux = 0;
    for (j=0; j<5; j++)
    {
        aux = aux + f.amount[j].value;
    }
    if (aux==0) {
        alert('Please, you have to type at least one form of payment. Try again. ');
        return false;
    }
    else{
        return true;
    }

 
} 

function validateInputMustBeNumber(vfield,e) 
{
    var key = '';
    var fulldata = '';
    var i = 0;
    var len = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode;
   

    if (document.all) { 
        var e = window.event 
        whichCode = e.keyCode 
    } else {
        whichCode = e.which 
    }
    if (whichCode == 13) return true; // Enter
    if (whichCode == 8)  return true; // Backspace
    if (whichCode == 0) return true;

    key = String.fromCharCode(whichCode);           // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    vfield.value += key; 
    return false;

}  


function allowOnlyTabKeyPressed(e) { 
    var keyStroked 
    if (document.all) { 
        var e = window.event   
        keyStroked = e.keyCode 
    } else {
        keyStroked = e.which 
    }
    if (keyStroked== 9) return true; //Tab Key
    if (keyStroked== 37) return true; //Back Arrow
    if (keyStroked== 39) return true; //Foward Arrow
    if (keyStroked== 38) return true; //Up Arrow
    if (keyStroked== 40) return true; //Down Arrow

    return false;
   
} 


function disableShiftTabKeyOnStripeData(e)
{                                                  
    var isShiftPressed = false;
    var isTabPressed = false;

    if (document.all) {  
        if (window.event.shiftKey) {   
            isShiftPressed = true;      
            if(window.event.keyCode == 9) {
                isTabPressed = true;
            } else {
                isTabPressed = false;
            }
        }
    } else {
        isShiftPressed = e.shiftKey;    
        if(e.keyCode == 9) {
            isTabPressed = true;
        } else {
            isTabPressed = false;
        }
    }
    if (isShiftPressed && isTabPressed) { 
        alert('This is the first field in the form.'); 
        return false; 
    } else {              
        return true;
    }
}

function disableShiftTabCtrlTabKeyOnButton(e)
{                                                  
    var isShiftPressed = false;
    var isTabPressed = false;
    var isCtrlPressed = false;

    if (document.all) {  
        if (window.event.shiftKey) {   
            isShiftPressed = true;     
        } 
        if (window.event.ctrlKey) {   
            isCtrlPressed = true;     
        } 
        if(window.event.keyCode == 9) {
            isTabPressed = true;
        } else {
            isTabPressed = false;
        }        
        
    } else {
        isShiftPressed = e.shiftKey; 
        isCtrlPressed  = e.ctrlKey; 
        if(e.keyCode == 9) {
            isTabPressed = true;
        } else {
            isTabPressed = false;
        }
    }   
    if (isShiftPressed || isCtrlPressed) {
        $$('#modal_container input[id*=_stripedata]')[0].focus();       
    }
         
    return true;
    
}

function disableShiftTabCtrlTabKeyOnInactivityW(e)
{                                                  
    var isShiftPressed = false;
    var isTabPressed = false;
    var isCtrlPressed = false;

    if (document.all) {  
        if (window.event.shiftKey) {   
            isShiftPressed = true;     
        } 
        if (window.event.ctrlKey) {   
            isCtrlPressed = true;     
        } 
        if(window.event.keyCode == 9) {
            isTabPressed = true;
        } else {
            isTabPressed = false;
        }        
        
    } else {
        isShiftPressed = e.shiftKey; 
        isCtrlPressed  = e.ctrlKey; 
        if(e.keyCode == 9) {
            isTabPressed = true;
        } else {
            isTabPressed = false;
        }
    }   
    if (isShiftPressed || isCtrlPressed) {
        alert('This is the first field in the form.'); 
        $$('#modal_container input[id*=password]')[0].focus(); 
        return false;      
    }
         
    return true;
    
}

function disableShiftTabKeyOnPassword(e)
{                                                  
    var isShiftPressed = false;
    var isTabPressed = false;

    if (document.all) {  
        if (window.event.shiftKey) {   
            isShiftPressed = true;      
            if(window.event.keyCode == 9) {
                isTabPressed = true;
            } else {
                isTabPressed = false;
            }
        }
    } else {
        isShiftPressed = e.shiftKey;    
        if(e.keyCode == 9) {
            isTabPressed = true;
        } else {
            isTabPressed = false;
        }
    }
    if (isShiftPressed && isTabPressed) { 
        alert('This is the first field in the form.'); 
        return false; 
    } else {              
        return true;
    }
}

function wait(msecs)
{
    var start = new Date().getTime();
    var cur = start
    while( msecs > cur - start)
    {
        cur = new Date().getTime();
    }
}

function stopRKey(evt) { 
    evt = (evt) ? evt : ((event) ? event : null); 
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
    if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} return true;
} 

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : evt.keyCode
    return (charCode <= 13 || (charCode >= 48 && charCode <= 57) || charCode == 46);
}